<template>
	<view class="publishJob">
		<view class="publishJob-content">
			<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData">
				<view class="formLabel no-border border-bottom"><text>服务经历<text class="red">*</text></text>
					<uni-forms-item name="title">
						<uni-easyinput v-model="valiFormData.title" placeholder="请输入服务经历标题" />
					</uni-forms-item>
				</view>
				<view class="formLabel">
					<text class="margin-right">服务时间</text>
					<uni-forms-item name="date">
						<uni-datetime-picker v-model="range" type="daterange" rangeSeparator="至" fields="day" />
					</uni-forms-item>
				</view>
				<view class="formLabel">
					<text>服务内容<text class="red">*</text></text>
					<uni-forms-item name="content">
						<uni-easyinput maxlength="300" type="textarea" v-model="valiFormData.content"
							placeholder="请简要描述服务内容及结果" />
					</uni-forms-item>
				</view>
				<view class="imgBox">
					<uni-file-picker title="添加图片" v-model="imageValue" fileMediatype="image" sourceType="['camera']"
						sizeType="['compressed']" :auto-upload="false" mode="grid" limit="5" @select="selectImg"
						@progress="progress" @success="success" @fail="fail" @delete="deleteImg" />
				</view>
			</uni-forms>
		</view>
		<view class="fixed-bottom-buttons">
			<view class="uni-flex uni-align-center uni-justify-between">
				<view class="button publish-job" @click="cancel">取消</view>
				<view class="button publish-demand" @click="setImageTranForm">保存</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onUnmounted,
		watch,
		getCurrentInstance,
		onMounted
	} from "vue";
	import {
		editService
	} from "@/api/contract.js";
	import {
		qiNiuFileUpload
	} from "@/utils/qiniu.js";
	import dayjs from 'dayjs';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	// 响应式数据
	const isChecked = ref(false);
	const submitFlag = ref(false);
	const userid = ref("");
	const valiForm = ref();
	const imageValue = ref([]);
	const imgPaths = ref([]);
	const eventChannel = getCurrentInstance().proxy.getOpenerEventChannel();
	// 表单数据
	const valiFormData = reactive({
		title: "",
		content: "",
		images: "",
		startDate: "",
		endDate: "",
		categoryId: "",
		id: 0,
		userId: ""
	});
	const range = ref([])
	// 处理日期选择变化
	const handleDateChange = (e) => {
		if (Array.isArray(e) && e.length === 2) {
			valiFormData.startDate = e[0];
			valiFormData.endDate = e[1];
		}
	};
	const formattedDate = dayjs(valiFormData.startDate).format('YYYY-MM-DD');
	// 监听 range 的变化
	watch(range, (newVal) => {
		if (Array.isArray(newVal) && newVal.length === 2) {
			valiFormData.startDate = newVal[0];
			valiFormData.endDate = newVal[1];
		}
	}, {
		deep: true
	});

	// 校验规则
	const rules = reactive({
		title: {
			rules: [{
				required: true,
				errorMessage: "标题不能为空"
			}]
		},
		content: {
			rules: [{
				required: true,
				errorMessage: "服务内容不能为空"
			}]
		}
	});

	// 处理图片回显逻辑
	onLoad((options) => {
		if (options.item) {
			const item = JSON.parse(decodeURIComponent(options.item));
			console.log('接收到的item:', item);

			// 填充表单数据
			valiFormData.title = item.title || "";
			valiFormData.content = item.content || "";
			valiFormData.images = item.imgFullUrls || "";
			valiFormData.startDate = item.startDate || "";
			valiFormData.endDate = item.endDate || "";
			valiFormData.id = item.id || 0; // 如果是编辑，保留原ID

			// 设置日期范围
			if (item.startDate && item.endDate) {
				range.value = [item.startDate, item.endDate];
			}

			// 处理回显图片 - 关键修复点
			if (item.imgFullUrls) {
				const imageUrls = item.imgFullUrls.split(',');
				const processedImages = imageUrls.map(url => {
					// 生成唯一ID，标记为远程图片，并提取key
					const key = url.split('/').pop(); // 假设URL最后一部分是key
					return {
						uuid: Date.now() + Math.random().toString(36).substring(2),
						path: url, // 图片完整URL
						key: key, // 七牛云存储的key
						isRemote: true // 标记为远程图片，不上传
					};
				});
				imageValue.value = processedImages.map(img => ({
					url: img.path,
					uuid: img.uuid,
					path: img.path
				}));
				imgPaths.value = processedImages;
			}
		}
	});

	// 获取上传状态
	const selectImg = (e) => {
		// 新选择的图片（本地临时路径）
		const tempFiles = e.tempFiles.map((item) => ({
			uuid: item.uuid,
			path: item.path, // 本地临时路径，如 `_doc/xxx.jpg`
			key: `images/resume/${userid.value}/${Date.now()}_${item.name}`,
			isRemote: false // 标记为本地图片
		}));
		imgPaths.value = [...imgPaths.value, ...tempFiles];
	};
	const deleteImg = e => {
		imgPaths.value = imgPaths.value.filter(item => {
			return item.uuid != e.tempFile.uuid;
		});
	};
	// 获取上传进度
	const progress = e => {
		console.log("上传进度：", e);
	};

	// 上传成功
	const success = e => {
		console.log("上传成功");
	};

	// 上传失败
	const fail = e => {
		console.log("上传失败：", e);
	};
	const cancel = () => {
		uni.navigateBack({
			delta: 1
		});
	};
	const save = () => {
		uni.navigateBack({
			delta: 1
		});
	};

	// 先处理图片，在上传
	const setImageTranForm = async () => {
		console.log(' imgPaths.value', imgPaths.value);
		try {
			await valiForm.value.validate();
			const form = {
				...valiFormData,
				userId: userid.value
			};

			// 过滤出需要上传的本地图片（isRemote为false）
			const filesToUpload = imgPaths.value.filter(file => !file.isRemote);
			console.log('filesToUpload', filesToUpload);

			// 收集已有的远程图片key
			const existingRemoteImages = imgPaths.value
				.filter(file => file.isRemote)
				.map(file => file.key);
			console.log('existingRemoteImages', existingRemoteImages);

			if (filesToUpload.length > 0) {
				submitFlag.value = true;
				uni.showLoading({
					title: "上传中..."
				});

				qiNiuFileUpload(
					filesToUpload,
					(filestr) => {
						// 合并新上传的图片和已有的远程图片
						const newUploadedImages = filestr.split(',');
						form.images = [...existingRemoteImages, ...newUploadedImages].join(',');

						submit(form);
					},
					(error) => {
						submitFlag.value = false;
						uni.hideLoading();
						uni.showToast({
							title: "上传图片失败！",
							icon: "none"
						});
					}
				);
			} else {
				// 没有新图片时，直接使用已有的远程图片
				form.images = existingRemoteImages.join(',');
				submit(form);
			}
		} catch (e) {
			console.error('表单验证失败:', e);
		}
	};

	const submit = (form) => {
		editService(form).then((res) => {
			uni.showToast({
				title: "保存成功",
				icon: "success"
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}).catch(err => {
			uni.showToast({
				title: "保存失败",
				icon: "none"
			});
		}).finally(() => {
			submitFlag.value = false;
			uni.hideLoading();
		});
	};

	onMounted(() => {
		const userinfo = uni.getStorageSync("user_info");
		if (userinfo) {
			userid.value = JSON.parse(userinfo).id;
		}
	});
</script>
<style lang="scss">
	.formLabel {
		.uni-forms-item {
			flex: 1;
			margin-bottom: 10rpx;
		}

		input {
			padding-left: 0;
		}

		.uni-easyinput__content-textarea {
			background: #f6f6f6;
			margin: 0 !important;
			padding: 20rpx;
		}
	}

	.no-border {
		.uni-forms-item__content .is-input-border {
			border: none !important;
			font-size: 28rpx;
			margin-top: 6rpx;
		}
	}

	.no-border-textarea {
		.uni-forms-item__content .is-input-border {
			border: none !important;
		}
	}
</style>

<style scoped lang="scss">
	.publishJob {
		padding: 26rpx 24rpx 0;
		background: #f5f5f5;
		min-height: calc(100vh - 26rpx);
		position: relative;

		.publishJob-content {
			background: #ffffff;
			border-radius: 20rpx;
			padding: 34rpx 26rpx 0 23rpx;
			min-height: calc(100vh - 250rpx);

			.imgBox {
				margin: 20rpx 0 0 0;
			}

			.border-bottom {
				border-bottom: 1px solid #e2e2e2;
			}

			.formLabel {
				text {
					font-weight: 500;
					font-size: 28rpx;
					color: #303133;
					line-height: 80rpx;
				}

				.red {
					color: #dd524d;
				}
			}

			.margin-right {
				margin-right: 40rpx;
			}
		}

		.fixed-bottom-buttons {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 154rpx;
			background: #ffffff;
			padding: 12rpx 23rpx 0;

			.button {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				color: #ffffff;

				&.publish-job {
					height: 88rpx;
					background: #fff;
					border-radius: 44rpx;
					margin-right: 61rpx;
					font-weight: 600;
					font-size: 30rpx;
					color: #666666;
					line-height: 88rpx;
					border: 1px solid #666;
				}

				&.publish-demand {
					height: 88rpx;
					background: #2f80ed;
					border-radius: 44rpx;
					font-weight: 600;
					font-size: 30rpx;
					color: #ffffff;
					line-height: 88rpx;
				}
			}
		}
	}
</style>